﻿using System;
using System.Globalization;
using System.Web.UI;

namespace HeroldIT.Dnn.Modules
{
    /// <summary>
    /// Provides helper methods for user interface generation.
    /// </summary>
    public static class UIHelper
    {
        #region constants

        /// <summary>
        /// Holds the limitChars function javascript code.
        /// </summary>
        private const string LimitCharsJs = "function limitChars(e,a){var key=e.which||((e.charCode||e.charCode===0)?e.charCode:e.keyCode);return((key==null)||(key==0)||(key==8)||(key==9)||(key==13)||(key==27)||(a.indexOf(String.fromCharCode(key))>=0));}";

        /// <summary>
        /// Holds the NumOnly event handler calling code.
        /// </summary>
        private const string LimitCharsCallJsFormat = "return limitChars(event,'{0}');";

        #endregion

        #region static methods

        /// <summary>
        /// Register the limitChars javascript code block with the page's ClientScript manager.
        /// </summary>
        /// <param name="page">The <see cref="Page"/> for which to register the limitChars javascript code block.</param>
        public static void RegisterLimitCharsJs(this Page page)
        {
            page.ClientScript.RegisterClientScriptBlock(typeof(UIHelper), "LimitCharsJs", LimitCharsJs, true);
        }

        /// <summary>
        /// Gets a call to the limitChars function for use in client event handlers.
        /// </summary>
        /// <param name="page">The <see cref="Page"/> on which the script is used.</param>
        /// <returns>A call to the limitChars function for use in client event handlers.</returns>
        public static string GetNumOnlyHandlerScript(this Page page)
        {
            page.RegisterLimitCharsJs();

            return page.GetLimitCharsHandlerScript("0123456789");
        }

        /// <summary>
        /// Gets a call to the limitChars function for use in client event handlers.
        /// </summary>
        /// <param name="page">The <see cref="Page"/> on which the script is used.</param>
        /// <param name="allowedChars">The characters allowed to be entered.</param>
        /// <returns>A call to the limitChars function for use in client event handlers.</returns>
        public static string GetLimitCharsHandlerScript(this Page page, string allowedChars)
        {
            page.RegisterLimitCharsJs();

            return String.Format(CultureInfo.InvariantCulture, LimitCharsCallJsFormat, allowedChars);
        }

        #endregion
    }
}
